﻿
/*******************************************************************************************
// ©2009 Microsoft Corporation.  This code is provided under the Microsoft Public License.
*******************************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Diagnostics;

namespace ClientBilling
{
    public partial class ExtendedWindow : System.Web.UI.Page
    {
        #region Constants
        public const string CONVERSATION_ID_QUERY_STRING = "convId";
        private const string ALLOCATIONS_CHANGED = "Allocations changed.";
        private const string ALLOCATIONS_NOT_SUMMING_CORRECTLY = "Allocations do not yet equal 100%.";
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadConversation();
            }
        }

        #region Load

        private void LoadConversation()
        {
            // Check for a query string containing the conversation ID.
            // If it's present, store the conversation ID in a hidden field.
            if (Request.QueryString[CONVERSATION_ID_QUERY_STRING] != null)
            {
                ConversationIdField.Value = Request.QueryString[CONVERSATION_ID_QUERY_STRING];
            }

            // Grab the client from the BilledCallTracker based on the conversation ID.
            Client client = BilledCallTracker.GetClientForBilledConversationId(ConversationIdField.Value);

            Debug.Assert(client != null, "client != null");

            LoadClient(client);
        }

        private void LoadClient(Client client)
        {
            ClientLabel.Text = client.Name;
            ClientNotesLiteral.Text = client.Notes;
            CaseRepeater.DataSource = BilledCallTracker.GetAllocationsForConversation(ConversationIdField.Value);
            CaseRepeater.DataBind();
        }

        #endregion

        #region Repeater Data Binding

        protected void CaseRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            TextBox box = e.Item.FindControl("AllocationBox") as TextBox;
            CheckBox checkBox = e.Item.FindControl("AllocationCheckBox") as CheckBox;

            CaseAllocation allocation = e.Item.DataItem as CaseAllocation;

            Debug.Assert(box != null, "box != null");
            Debug.Assert(allocation != null, "allocation != null");

            if (!IsPostBack)
            {
                // Display the allocation percentage for the case.
                box.Text = (allocation.PortionOfCall * 100).ToString();
                checkBox.Checked = allocation.PortionOfCall > 0;
                box.Enabled = checkBox.Checked;
            }
        }

        #endregion

        #region Handle Allocation Changes

        protected void AllocationBox_TextChanged(object sender, EventArgs e)
        {
            SetAllocationsFromTextBoxes();
        }

        /// <summary>
        /// Pass the allocations from the text boxes on the page to the BilledCallTracker,
        /// first checking that they sum correctly.
        /// </summary>
        private void SetAllocationsFromTextBoxes()
        {
            // First, we get the allocations currently stored for this conversation.
            List<CaseAllocation> allocations = BilledCallTracker.GetAllocationsForConversation(ConversationIdField.Value);

            decimal newPercentage;
            TextBox box;

            // Next, we set the allocation percentages based on the values entered on the page.
            for (int i = 0; i < allocations.Count; i++)
            {
                box = CaseRepeater.Items[i].FindControl("AllocationBox") as TextBox;
                newPercentage = decimal.Parse(box.Text);

                // We convert the values from percentages (0 to 100) to values between 0 and 1.
                allocations[i].PortionOfCall = (newPercentage / 100);
            }

            decimal sum = 0;

            // Next, we sum up the allocations to make sure they sum to one.
            foreach (CaseAllocation newAllocation in allocations)
            {
                sum += newAllocation.PortionOfCall;
            }

            if (sum == 1)
            {
                // If they do sum to one, we pass along the allocations to the BilledCallTracker for storage.
                BilledCallTracker.SetAllocationsForConversation(ConversationIdField.Value, allocations);
                MessageLabel.Text = ALLOCATIONS_CHANGED;
            }
            else
            {
                // If they don't sum to one, we display an error message.
                MessageLabel.Text = ALLOCATIONS_NOT_SUMMING_CORRECTLY;
            }
        }

        protected void CheckBox_CheckChanged(object sender, EventArgs e)
        {
            // Get references to the controls.
            CheckBox box = sender as CheckBox;
            RepeaterItem repeaterItem = box.Parent as RepeaterItem;
            TextBox allocationBox = repeaterItem.FindControl("AllocationBox") as TextBox;

            // Enable the text box if the check box is checked; otherwise disable it.
            allocationBox.Enabled = box.Checked;

            // Redistribute the allocations equally across all the checked cases.
            RedistributeAllocations();
        }

        protected void PlusButton_Click(object sender, EventArgs e)
        {
            // Get references to the controls.
            Button btn = sender as Button;
            RepeaterItem repeaterItem = btn.Parent as RepeaterItem;
            TextBox allocationBox = repeaterItem.FindControl("AllocationBox") as TextBox;

            // Find out the current percentage.
            int currentPercentage = int.Parse(allocationBox.Text);

            if (currentPercentage <= 95) // Don't let the percentage go above 100.
            {
                if (allocationBox.Enabled == false)
                {
                    // If this allocation is unchecked, check it.
                    CheckBox checkBox = repeaterItem.FindControl("AllocationCheckBox") as CheckBox;
                    checkBox.Checked = true;
                    allocationBox.Enabled = true;
                }

                // Increase the allocation percentage by 5.
                allocationBox.Text = (currentPercentage + 5).ToString();

                // Send along the entered allocations to the BilledCallTracker.
                SetAllocationsFromTextBoxes();
            }
        }

        protected void MinusButton_Click(object sender, EventArgs e)
        {
            // Get references to the controls.
            Button btn = sender as Button;
            RepeaterItem repeaterItem = btn.Parent as RepeaterItem;
            TextBox allocationBox = repeaterItem.FindControl("AllocationBox") as TextBox;

            // Find out the current percentage.
            int currentPercentage = int.Parse(allocationBox.Text);

            if (currentPercentage >= 5) // Don't let the percentage go below zero.
            {
                if (allocationBox.Enabled == false)
                {
                    // If this allocation is unchecked, check it.
                    CheckBox checkBox = repeaterItem.FindControl("AllocationCheckBox") as CheckBox;
                    checkBox.Checked = true;
                    allocationBox.Enabled = true;
                }

                // Decrease the allocation percentage by 5.
                allocationBox.Text = (currentPercentage - 5).ToString();

                // Send along the entered allocations to the BilledCallTracker.
                SetAllocationsFromTextBoxes();
            }
        }

        /// <summary>
        /// Distribute the call allocation evenly across all of the selected cases.
        /// </summary>
        private void RedistributeAllocations()
        {
            List<CaseAllocation> allocations = BilledCallTracker.GetAllocationsForConversation(ConversationIdField.Value);

            int numberOfBoxesChecked = 0;

            CheckBox allocationCheckBox;

            // Iterate through the repeater items and count how many check boxes are checked.
            foreach (RepeaterItem repeaterItem in CaseRepeater.Items)
            {
                allocationCheckBox = repeaterItem.FindControl("AllocationCheckBox") as CheckBox;
                if (allocationCheckBox.Checked)
                    numberOfBoxesChecked++;
            }

            // Figure out what percentage to assign to each of the checked allocations
            // so that they sum to 100%.
            decimal newPercentage = 100 / numberOfBoxesChecked;

            TextBox box;

            // Iterate through the repeater items, and put the new allocation
            // percentage that we calculated into each text box that is enabled.
            for (int i = 0; i < allocations.Count; i++)
            {
                box = CaseRepeater.Items[i].FindControl("AllocationBox") as TextBox;

                if (box.Enabled)
                {
                    // Set the checked allocations to equal shares of the total.
                    box.Text = newPercentage.ToString();
                    allocations[i].PortionOfCall = (newPercentage / 100);
                }
                else
                {
                    // Set the unchecked allocations to zero. 
                    allocations[i].PortionOfCall = 0;
                    box.Text = allocations[i].PortionOfCall.ToString();
                }
            }

            // Pass along the new allocations to the BilledCallTracker.
            BilledCallTracker.SetAllocationsForConversation(ConversationIdField.Value, allocations);

            MessageLabel.Text = ALLOCATIONS_CHANGED;
        }

        #endregion
    }
}
